import { ForbiddenException, HttpException, Injectable, UnauthorizedException } from '@nestjs/common';
import { UserService } from '../user/user.service';
import { JwtService } from '@nestjs/jwt';
import * as argon2 from "argon2"
@Injectable()
export class AuthService {
  constructor(private userService: UserService, private jwtService: JwtService) {
  }

  async signin(username: string, password: string) {
    const user = await this.userService.find(username);
    if(!user){
      throw new ForbiddenException('用户不存在请注册')
    }
    const isPasswordValid=await argon2.verify(user.password,password)
    if(isPasswordValid){
      return this.jwtService.signAsync({
        username:user.username,
        sub:user.id
      })
    }
    throw new ForbiddenException('用户名或密码错误')
  }

  async signup(username: string, password: string) {
    if (!username || !password) {
      throw new HttpException('用户名或者密码不能为空', 400);
    }
    const user = await this.userService.find(username);
    if(user){
      throw new ForbiddenException('用户已存在')
    }
    const res = this.userService.create({
      username,
      password,
    });
    return res;
  }
}
